<?php
class FileSystem{
	private $db;
	private $log;
	private $guest_uid = 0;
	function __construct($db,$log){
		$this->db = $db;
		$this->log = $log;
	}
	
	public function getFileByMD5($md5){
		$sql = "select * from t_file where md5='$md5";
		return $this->db->query_assoc($sql);
	}
	public function getFileById($fid){
		$sql = "select * from t_file where fid='$fid'";
		return $this->db->query_assoc($sql);
	}
	public function saveFile($uid,$filedata){
		if(!$uid){
			$uid = $this->$guest_uid;
		}
		/*
		if(!$uid || !$filedata){
			$this->log->log("用户未登录或文件数据不存在！");
			return "用户未登录或文件数据不存在！";
		}
		*/
		$tmpfile = $filedata["tmp_name"];
		$fname = $filedata["name"];
		$fmtime = filemtime($tmpfile);
		$fsize = $filedata["size"];
		$ip = $_SERVER[REMOTE_ADDR];

		/* 保存文件 */
		$fmd5 = md5_file($tmpfile);
		$file = $this->getFileByMD5($fmd5);
		if($file){//已经存在
			$fid = $file[fid];
		}else{//不存在
			$fid = util::randID();
			//保存文件到系统
			$res = move_uploaded_file($tmpfile,$file);
			if($res==false){
				$this->log->log("保存文件到用户目录时出错！");
				return "保存文件失败!";
			}
			//将文件信息保存到数据库
			$sql = "insert into t_file(fid,fmd5,fsize,fmtime,fpath,upload_uid,upload_time) values('$fid','$fmd5',$fsize,$fmtime,'$fid',$uid,".time().")";
			$res = $this->db->update($sql);
			if(!$res){
				return "保存文件信息到数据库出错！";
			}
		}
		
		/* 关联文件与用户 */
		if(!$this->checkExists($uid,$fid)){
			$futime = time();
			$fstatus = 0;
			
			$sql = "insert into t_user_file(uid,fid,fname,futime,fstatus,user_ip) values($uid,'$fid','$fname',$futime,$fstatus,'$ip')";
			$res = $this->db->update($sql);
			if(!$res){
				return "关联用户和文件时出错！";
			}
		}
		return null;
	}
	
	public function getRootDirectory(){
		$sql = "select value from t_sysconfig where `key`='file.rootdir'";
		return $this->db->query_first($sql);
	}
	/**
	 * 判断是否已经存在该文件
	 * @param int $uid
	 * @param unknown_type $file
	 */
	public function checkExists($uid,$fid){
		$sql = "select count(*) from t_user_file where uid='$uid' and fid='$fid'";
		$count = $this->db->query_first($sql);
		return $count>0;
	}
}
?>